<template>
  <div class="debug-test">
    <h2>Tinyflow调试测试</h2>

    <div class="debug-info">
      <h3>调试信息</h3>
      <div class="info-item"><strong>状态:</strong> {{ status }}</div>
      <div class="info-item"><strong>错误:</strong> {{ error || '无' }}</div>
      <div class="info-item"><strong>实例:</strong> {{ instanceStatus }}</div>
    </div>

    <div class="designer-container">
      <div ref="tinyflowContainer" class="tinyflow-canvas"></div>
    </div>

    <div class="controls">
      <button @click="debugInstance">调试实例</button>
      <button @click="getData">获取数据</button>
      <button @click="checkNodes">检查节点</button>
      <button @click="reload">重新加载</button>
    </div>

    <div class="data-display">
      <h3>工作流数据</h3>
      <pre>{{ workflowData }}</pre>
    </div>

    <div class="console-output">
      <h3>控制台输出</h3>
      <div class="console-content">
        <div v-for="(log, index) in consoleLogs" :key="index" class="log-item">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-level" :class="log.level">{{
            log.level.toUpperCase()
          }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { Tinyflow } from '@tinyflow-ai/ui';
import '@tinyflow-ai/ui/dist/index.css';

const tinyflowContainer = ref<HTMLElement>();
let tinyflowInstance: any = null;
const workflowData = ref('');
const status = ref('未初始化');
const error = ref('');
const instanceStatus = ref('未创建');
const consoleLogs = ref<
  Array<{ time: string; level: string; message: string }>
>([]);

// 添加日志函数
const addLog = (level: string, message: string) => {
  const time = new Date().toLocaleTimeString();
  consoleLogs.value.push({ time, level, message });
  console[level](message);
};

// 简单的Provider配置
const simpleProvider = {
  internal: () => {
    addLog('info', 'Provider.internal() 被调用');
    return [
      {
        value: 'test-node',
        label: '测试节点',
        icon: 'ant-design:play-circle-outlined',
      },
    ];
  },
  knowledge: () => {
    addLog('info', 'Provider.knowledge() 被调用');
    return [];
  },
  llm: () => {
    addLog('info', 'Provider.llm() 被调用');
    return [];
  },
};

// 简单的自定义节点
const simpleCustomNodes = {
  'custom-test': {
    title: '自定义测试节点',
    description: '这是一个测试自定义节点',
    icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L2 7v10c0 5.55 3.84 9.74 9 11 5.16-1.26 9-5.45 9-11V7l-10-5z"></path></svg>',
    sortNo: 1,
    group: 'base' as const,
    render: (parent: any, node: any, flowInstance: any) => {
      addLog('info', `渲染自定义节点: ${node.id}`);
      addLog('info', `节点数据: ${JSON.stringify(node.data)}`);

      parent.innerHTML = `
        <div style="padding: 8px; background: #e6f7ff; border: 1px solid #91d5ff; border-radius: 4px;">
          <div style="font-weight: bold; margin-bottom: 4px; color: #1890ff;">自定义测试节点</div>
          <div style="font-size: 12px; color: #666;">ID: ${node.id}</div>
          <div style="font-size: 12px; color: #666;">类型: ${node.type}</div>
        </div>
      `;
    },
    onUpdate: (parent: any, node: any) => {
      addLog('info', `自定义节点更新: ${node.id}`);
    },
  },
};

// 初始化Tinyflow
const initTinyflow = () => {
  if (tinyflowContainer.value) {
    status.value = '正在初始化...';
    error.value = '';
    instanceStatus.value = '创建中...';

    addLog('info', '开始初始化Tinyflow...');
    addLog('info', `容器元素: ${tinyflowContainer.value.tagName}`);
    addLog('info', `Provider配置: ${JSON.stringify(simpleProvider, null, 2)}`);
    addLog(
      'info',
      `自定义节点配置: ${JSON.stringify(simpleCustomNodes, null, 2)}`,
    );

    try {
      const config = {
        element: tinyflowContainer.value,
        data: {
          nodes: [],
          edges: [],
          viewport: { x: 0, y: 0, zoom: 1 },
        },
        provider: simpleProvider,
        customNodes: simpleCustomNodes,
      };

      addLog('info', `Tinyflow配置: ${JSON.stringify(config, null, 2)}`);

      tinyflowInstance = new Tinyflow(config);

      addLog('success', 'Tinyflow实例创建成功');
      status.value = '初始化成功';
      instanceStatus.value = '已创建';

      // 检查实例方法
      const methods = Object.getOwnPropertyNames(tinyflowInstance);
      addLog('info', `实例方法: ${methods.join(', ')}`);

      if (typeof tinyflowInstance.getData === 'function') {
        addLog('success', 'getData方法存在');
      } else {
        addLog('warn', 'getData方法不存在');
      }
    } catch (err: any) {
      addLog('error', `Tinyflow初始化失败: ${err.message}`);
      error.value = err.message || '初始化失败';
      status.value = '初始化失败';
      instanceStatus.value = '创建失败';
    }
  } else {
    addLog('error', '容器元素未找到');
    error.value = '容器元素未找到';
    status.value = '初始化失败';
    instanceStatus.value = '容器未找到';
  }
};

onMounted(() => {
  initTinyflow();
});

// 销毁Tinyflow
onUnmounted(() => {
  if (tinyflowInstance) {
    try {
      tinyflowInstance.destroy();
      tinyflowInstance = null;
      addLog('info', 'Tinyflow实例已销毁');
    } catch (err: any) {
      addLog('error', `Tinyflow销毁失败: ${err.message}`);
    }
  }
});

// 调试实例
const debugInstance = () => {
  if (tinyflowInstance) {
    addLog('info', '=== 调试Tinyflow实例 ===');
    addLog('info', `实例类型: ${typeof tinyflowInstance}`);
    addLog('info', `实例构造函数: ${tinyflowInstance.constructor.name}`);

    const methods = Object.getOwnPropertyNames(tinyflowInstance);
    addLog('info', `所有方法: ${methods.join(', ')}`);

    // 检查原型链
    const prototype = Object.getPrototypeOf(tinyflowInstance);
    const prototypeMethods = Object.getOwnPropertyNames(prototype);
    addLog('info', `原型方法: ${prototypeMethods.join(', ')}`);

    instanceStatus.value = '调试完成';
  } else {
    addLog('warn', 'Tinyflow实例不存在');
    instanceStatus.value = '实例不存在';
  }
};

// 获取数据
const getData = () => {
  if (tinyflowInstance) {
    try {
      const data = tinyflowInstance.getData();
      workflowData.value = JSON.stringify(data, null, 2);
      addLog('success', '获取到工作流数据');
      addLog('info', `数据: ${JSON.stringify(data, null, 2)}`);
      status.value = '数据获取成功';
    } catch (err: any) {
      addLog('error', `获取数据失败: ${err.message}`);
      error.value = err.message || '获取数据失败';
      status.value = '数据获取失败';
    }
  } else {
    addLog('warn', 'Tinyflow实例未初始化');
    error.value = 'Tinyflow实例未初始化';
    status.value = '实例未初始化';
  }
};

// 检查节点
const checkNodes = () => {
  if (tinyflowInstance) {
    try {
      const data = tinyflowInstance.getData();
      const nodeCount = data?.nodes?.length || 0;
      const edgeCount = data?.edges?.length || 0;

      addLog('info', `节点数量: ${nodeCount}`);
      addLog('info', `连接数量: ${edgeCount}`);

      if (data?.nodes) {
        data.nodes.forEach((node: any, index: number) => {
          addLog('info', `节点${index + 1}: ${node.type} (${node.id})`);
        });
      }

      status.value = '节点检查完成';
    } catch (err: any) {
      addLog('error', `检查节点失败: ${err.message}`);
    }
  } else {
    addLog('warn', 'Tinyflow实例未初始化');
  }
};

// 重新加载
const reload = () => {
  addLog('info', '重新加载Tinyflow...');

  if (tinyflowInstance) {
    try {
      tinyflowInstance.destroy();
      tinyflowInstance = null;
      addLog('info', '旧实例已销毁');
    } catch (err: any) {
      addLog('error', `销毁旧实例失败: ${err.message}`);
    }
  }

  // 清空日志
  consoleLogs.value = [];

  // 重新初始化
  setTimeout(() => {
    initTinyflow();
  }, 100);
};
</script>

<style lang="less" scoped>
.debug-test {
  padding: 24px;

  h2 {
    margin-bottom: 16px;
    color: #1890ff;
  }

  .debug-info {
    margin-bottom: 16px;
    padding: 16px;
    background: #f5f5f5;
    border-radius: 6px;

    h3 {
      margin-bottom: 12px;
      color: #333;
    }

    .info-item {
      margin-bottom: 8px;
      font-family: monospace;
      font-size: 14px;

      strong {
        color: #1890ff;
      }
    }
  }

  .designer-container {
    height: 400px;
    border: 2px solid #e8e8e8;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 24px;

    .tinyflow-canvas {
      height: 100%;
      width: 100%;
      background: #fafafa;
    }
  }

  .controls {
    margin-bottom: 24px;

    button {
      margin-right: 12px;
      padding: 8px 16px;
      background: #1890ff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background: #40a9ff;
      }
    }
  }

  .data-display {
    margin-bottom: 24px;

    h3 {
      margin-bottom: 12px;
      color: #333;
    }

    pre {
      background: #f5f5f5;
      padding: 16px;
      border-radius: 6px;
      overflow: auto;
      max-height: 200px;
      font-size: 12px;
      border: 1px solid #e8e8e8;
    }
  }

  .console-output {
    h3 {
      margin-bottom: 12px;
      color: #333;
    }

    .console-content {
      background: #1e1e1e;
      color: #fff;
      padding: 16px;
      border-radius: 6px;
      max-height: 300px;
      overflow: auto;
      font-family: 'Courier New', monospace;
      font-size: 12px;

      .log-item {
        margin-bottom: 4px;

        .log-time {
          color: #888;
          margin-right: 8px;
        }

        .log-level {
          margin-right: 8px;
          font-weight: bold;

          &.info {
            color: #4fc3f7;
          }

          &.success {
            color: #4caf50;
          }

          &.warn {
            color: #ff9800;
          }

          &.error {
            color: #f44336;
          }
        }

        .log-message {
          color: #fff;
        }
      }
    }
  }
}
</style>
